//
//  HDAnnotationView.m
//  HDMapKit
//
//  Created by Liuzhuan on 13-4-8.
//  Copyright (c) 2013年 hengdawb. All rights reserved.
//

#import "HDAnnotationView.h"
#import "HDCallOutView.h"
#import <QuartzCore/QuartzCore.h>
#import "UIButton+WebCache.h"
#import "HD_NKM_MapView.h"
#import "HD_NKM_Big_Ann_View.h"

@implementation HDAnnotationView {
    HDDeclare *declare;
    HD_NKM_Big_Ann_View *bigAnn;
}
#define RED_PIN             @"default_poi"
#define PIN_WIDTH           40.0  // POI图片大小，根据实际填写
#define PIN_HEIGHT          51.5

#define PIN_WIDTH_Ser          40.0  // POI图片大小，根据实际填写
#define PIN_HEIGHT_Ser         40.0

//10:13
#define PIN_POINT_X         8.0
#define PIN_POINT_Y         35.0
#define CALLOUT_OFFSET_X    7.0
#define CALLOUT_OFFSET_Y    5.0

#pragma mark -------- Init Methods --------
- (instancetype)initWithAnnotation:(HDAnnotation *)annotation onView:(HD_NKM_MapView *)mapView animated:(BOOL)animate {
	CGRect frame = CGRectMake(0, 0, 0, 0); // TODO: remove this
    
	if ((self = [super initWithFrame:frame])) {
		self.annotation = annotation;
        declare = [HDDeclare sharedDeclare];
        self.frame      = [self frameForPoint:annotation.point];
        
        UIImage *myImage = [UIImage imageNamed:RED_PIN];
        
        NSString *imgStr = [HDDeclare realSizeImagePathWithRequestPath:annotation.poiImgPath];//[HDDeclare URLImagePath:annotation.poiImgPath imgSize:self.size];//新的图片地址规则
        NSURL *poiImgURL = [NSURL URLWithString:imgStr];
        
        if (_annotation.isHighShow == YES)
        {
            imgStr = [HDDeclare realSizeImagePathWithRequestPath:annotation.poiBigPath];//[HDDeclare URLImagePath:annotation.poiBigPath imgSize:self.size];
            poiImgURL = [NSURL URLWithString:imgStr];
        }
        
        [self sd_setImageWithURL:poiImgURL forState:UIControlStateNormal placeholderImage:myImage];
        
//        UIImage *img = [UIImage imageWithContentsOfFile:self.annotation.poiImgPath];
//        
//        if (self.annotation.isPlay == kPlay_Status_Service_Info ) {
//            //设施类型1女厕所，2男厕所，3通用厕所，4电梯,5商店,6服务中心,7柜台,8咖啡吧,9开水间，10，右逃生，11，左逃生，12，直梯，13，扶梯
//            NSInteger type = self.annotation.serviceType.integerValue;
//            switch (type) {
//                case 1:
//                    myImage = [UIImage imageNamed:@"服务设施-女"];
//                    break;
//                case 2:
//                    myImage = [UIImage imageNamed:@"服务设施-男"];
//                    break;
//                case 3:
//                    myImage = [UIImage imageNamed:@"服务设施-卫生间"];
//                    break;
//                case 4:
//                    myImage = [UIImage imageNamed:@"服务设施-直梯"];
//                    break;
//                case 5:
//                    myImage = [UIImage imageNamed:@"服务设施-商店"];
//                    break;
//                case 6:
//                    myImage = [UIImage imageNamed:@"服务设施-服务"];
//                    break;
//                case 7:
//                    myImage = [UIImage imageNamed:@"服务设施-柜台"];
//                    break;
//                case 8:
//                    myImage = [UIImage imageNamed:@"服务设施-咖啡"];
//                    break;
//                case 9:
//                     myImage = [UIImage imageNamed:@"服务设施-饮水间"];
//                    break;
//                case 10:
//                    myImage = [UIImage imageNamed:@"服务设施-右逃生"];
//                    break;
//                case 11:
//                    myImage = [UIImage imageNamed:@"服务设施-左逃生"];
//                    break;
//                case 12:
//                    myImage = [UIImage imageNamed:@"服务设施-直梯"];
//                    break;
//                case 13:
//                    myImage = [UIImage imageNamed:@"服务设施-扶梯"];
//                    break;
//                default:
//                    break;
//            }
//            self.userInteractionEnabled = NO;
//        }
//        [self setImage:img forState:UIControlStateNormal];
//        
//        if (!img) {
//            [self setImage:myImage forState:UIControlStateNormal];
//        }
        self.imageView.contentMode = UIViewContentModeScaleAspectFit;
		[self addTarget:mapView
                 action:@selector(showCallOut:)
       forControlEvents:UIControlEventTouchDown];
        
        self.enabled = YES;
		[mapView addSubview:self];
	}
    
	return self;
}

#pragma mark
#pragma mark -------- Animation Methods --------

- (void)bigPicture
{
    bigAnn = [[[NSBundle mainBundle] loadNibNamed:@"HD_NKM_Big_Ann_View"
                                            owner:self
                                          options:nil] lastObject];
    
    [bigAnn.imgView setImage:self.imageView.image];
//    NSString *imgStr = [HDDeclare URLImagePath:_annotation.poiBigPath imgSize:bigAnn.imgView.size];//新的图片地址规则
    NSString *imgStr = [HDDeclare realSizeImagePathWithRequestPath:_annotation.poiBigPath];
    NSURL *poiImgURL = [NSURL URLWithString:imgStr];
    
    if (_annotation.isHighShow == NO)
        [bigAnn.imgView sd_setImageWithURL:poiImgURL];
    
    bigAnn.nameLabel.text = _annotation.title;
    bigAnn.myAnn = _annotation;
    [self setImage:nil forState:UIControlStateNormal];
    
    [self frameForBigAnn];
    [self addSubview:bigAnn];
    
    _isBig = YES;
}

// 放大后的UIView超出了当前的范围
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];
    if (view == nil && bigAnn != nil) {
        CGPoint tempoint = [bigAnn convertPoint:point fromView:self];
        if (CGRectContainsPoint(bigAnn.bounds, tempoint)) {
            view = bigAnn;
        }
    }
    return view;
}

- (void)frameForBigAnn
{
    CGSize frameSize = bigAnn.frame.size;
    CGSize size = self.frame.size;
    
    bigAnn.frame = CGRectMake((size.width - frameSize.width)/2, (-frameSize.width+size.height), frameSize.width, frameSize.height);
}

- (void)smallPicture
{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIImage *myImage = [UIImage imageNamed:RED_PIN];
        
        NSString *imgStr = [HDDeclare realSizeImagePathWithRequestPath:_annotation.poiImgPath];//[HDDeclare URLImagePath:_annotation.poiImgPath imgSize:self.size];//新的图片地址规则
        if (_annotation.isHighShow == YES)
            imgStr = [HDDeclare realSizeImagePathWithRequestPath:_annotation.poiBigPath];
        NSURL *poiImgURL = [NSURL URLWithString:imgStr];
        
        [self sd_setImageWithURL:poiImgURL forState:UIControlStateNormal placeholderImage:myImage];
        [bigAnn removeFromSuperview];
        bigAnn = nil;
        _isBig = NO;
    });
}

- (void)beginAnimate
{
    CGFloat originY = 0;
    CGFloat originX = self.imageView.frame.origin.x;
    CGFloat width = self.imageView.frame.size.width;
    CGFloat height = self.imageView.frame.size.height;
    
    if (upOrdown == NO) {
        num --;
        self.imageView.frame = CGRectMake(originX, originY+num, width, height);
        if (num == -5) {
            upOrdown = YES;
        }
    }
    else {
        num ++;
        self.imageView.frame = CGRectMake(originX, originY+num, width, height);
        if (num == 0) {
            upOrdown = NO;
        }
    }
}

- (void)stopAnimate
{
//    self.imageView.frame = CGRectMake(self.imageView.frame.origin.x, 0, self.imageView.frame.size.width, self.imageView.frame.size.height);
//
//    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(beginAnimate) object:nil];
//    [_timer invalidate];
//    self.timer = nil;
    [self.layer removeAnimationForKey:@"kViewShakerAnimationKey"];
    self.isAnimating = NO;
}

- (void)shakeToShow:(UIView*)aView{
    
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    
    animation.repeatCount = MAXFLOAT;
    animation.removedOnCompletion = NO;
    animation.duration = 2.0;// 动画时间
    animation.fillMode = kCAFillModeForwards;
    NSMutableArray *values = [NSMutableArray array];
    
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    
    // 这三个数字，我只研究了前两个，所以最后一个数字我还是按照它原来写1.0；前两个是控制view的大小的；
    
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.5, 1.5, 1.0)]];
    
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.5, 0.5, 1.0)]];
    
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    animation.values = values;
    [aView.layer addAnimation:animation forKey:nil];
    
}

- (void)popJumpAnimationView:(UIButton *)sender {
    CGFloat duration = 1.f;
    CGFloat height = 20.f;
    CAKeyframeAnimation * animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.y"];
    CGFloat currentTy = sender.transform.ty;
    animation.duration = duration;
    
    animation.values = @[@(currentTy), @(currentTy - height/4), @(currentTy-height/4*2), @(currentTy-height/4*3), @(currentTy - height), @(currentTy-height/4*3), @(currentTy -height/4*2), @(currentTy - height/4), @(currentTy)];
//    CGFloat t = 4;
//    animation.values = @[@(currentTy), @(currentTy - height/5), @(currentTy-height/t*2), @(currentTy-height/t*3), @(currentTy - height), @(currentTy-height/t*3), @(currentTy -height/t*2), @(currentTy - height/t), @(currentTy)];
    
    animation.keyTimes = @[ @(0), @(0.025), @(0.085), @(0.2), @(0.5), @(0.8), @(0.915), @(0.975), @(1) ];
    
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    
    animation.repeatCount = HUGE_VALF;
    
    [sender.layer addAnimation:animation forKey:@"kViewShakerAnimationKey"];
    self.isAnimating = YES;
}

- (void)locationChangeCenter:(CGPoint)point {
    
    CGFloat x = point.x - PIN_POINT_X;
    CGFloat y = point.y - PIN_POINT_Y;
    // 减去10是要扩大手势范围
    self.frame = CGRectMake(round(x)-10, round(y)-10, PIN_WIDTH, PIN_HEIGHT);
}

- (CGRect)frameForPoint:(CGPoint)point {
    
    CGFloat x = point.x - PIN_WIDTH/2.0;
    CGFloat y = point.y - PIN_HEIGHT;
    
    if (self.annotation.isPlay == kPlay_Status_Service_Info ) {
        CGFloat x = point.x - PIN_WIDTH_Ser/2.0;
        CGFloat y = point.y - PIN_WIDTH_Ser/2.0;
        return CGRectMake(round(x)-10, round(y)-10, PIN_WIDTH_Ser, PIN_WIDTH_Ser);
    }
    return CGRectMake(round(x), round(y), PIN_WIDTH, PIN_HEIGHT);
}

// 对mapview的放大倍数增加观察者，所有的POI根据放大倍数动态调整坐标
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqual:@"contentSize"]) {
        HD_NKM_MapView *mapView = (HD_NKM_MapView *)object;

        CGFloat      width   = (mapView.contentSize.width / mapView.orignalSize.width/mapView.minimumZoomScale) * self.annotation.point.x;
        CGFloat      height  = (mapView.contentSize.height / mapView.orignalSize.height/mapView.minimumZoomScale) * self.annotation.point.y;
        
        if (width>0&&height>0) {
            self.frame = [self frameForPoint:CGPointMake(width, height)];
        }
        
    }
}

// 或者是收号以后，更新，图片传入的是路径
- (void)changePOIImageWithPath:(NSString *)imgPath
{
    if (self.annotation.isPlay == kPlay_Status_No)
    { self.annotation.isPlay = kPlay_Status_Yes; }
    else if (self.annotation.isPlay == kPlay_Status_More)
    { self.annotation.isPlay = kPlay_Status_More_Read; }
    
    UIImage *myImage = [UIImage imageWithContentsOfFile:imgPath];
    if (myImage == nil)
        myImage = [UIImage imageNamed:RED_PIN];
    
    [self setImage:myImage forState:UIControlStateNormal];
}

- (void)dealloc
{
    [self stopAnimate];
    _annotation = nil;
}

@end
